package com.globaldom.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.Deployment;
import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

//FIXME PERF has high CPU utilization!!
@Controller
@RequestMapping(value = "/adddeployment")
public class DeploymentAddController {

	// private static final Logger log =
	// Logger.getLogger(DeploymentAddController.class.getName());

	public DeploymentAddController() {
	}
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model, HttpSession session) {
		return "errorpage";
	}

	// BUGFIX sanitize the inputs!
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> addMyDeployment(@RequestParam Long locID, @RequestParam long m0, @RequestParam long m1,
			@RequestParam long m2, @RequestParam long m3, @RequestParam long m4, @RequestParam long m5, Model model,
			HttpSession session, HttpServletRequest request) {

		Map<String, String> map = new HashMap<String, String>();
		long[] deps = new long[10];
		deps[0] = m0;
		deps[1] = m1;
		deps[2] = m2;
		deps[3] = m3;
		deps[4] = m4;
		deps[5] = m5;
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Map<Integer, Long> deltaMap = new HashMap<Integer, Long>();
//PERF get only the IDs!0
			Query query = pm.newQuery("Select id from "+ PersonLocation.class.getName() + " where id==locid && person==pid");
			query.declareParameters("long locid,String pid");
		 ((List)query.execute(locID, personID)).get(0);

			query = pm.newQuery(Deployment.class, "personLocation==locid");
			query.declareParameters("long locid");
			List<Deployment> deployment = (List<Deployment>) query.execute(locID);

			if (deployment.size() > 0) {
				Map<Integer, Long> engDep = new HashMap<Integer, Long>();
				for (Iterator<Deployment> iterator = deployment.iterator(); iterator.hasNext();) {
					Deployment curDeployed = (Deployment) iterator.next();
					curDeployed.setAvailResources(deps[curDeployed.getResourceType()]);
				}
				MemCacheManager.putDeployment(personID, locID.toString(), engDep);
			} else {
				List<Deployment> deployments = new ArrayList<Deployment>();
				for (int i = 0; i <= 5; i++) {
					Deployment dep = new Deployment();
					dep.setResourceType(i);
					dep.setAvailResources(deps[i]);
					dep.setPerson(personID);
					dep.setPersonLocation(locID);
					deployments.add(dep);

				}
			//	PersistenceManager pmf = PMF.get().getPersistenceManager();
				pm.makePersistentAll(deployments);
			//	pmf.close();
				MemCacheManager.putDeployment(personID, locID.toString(), deltaMap);
			}

			map.put(Constants.STATUS, "+OK");
			map.put(Constants.CODE, "200");

		} catch (Exception edea) {
			// FIXME. The said territory has been looted but the user is not
			// aware!
			MemCacheManager.removeDeployments(personID, locID.toString());
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "EDE");
		} finally {
			pm.close();
		}

		return map;
	}
}
